<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCP Memory Service - SSE Test</title>
    <style>
        body {
            font-family: 'Courier New', monospace;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            font-weight: bold;
        }
        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .controls {
            margin: 20px 0;
            text-align: center;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        .events-container {
            display: flex;
            gap: 20px;
        }
        .events-log {
            flex: 1;
            background-color: #000;
            color: #00ff00;
            padding: 15px;
            border-radius: 5px;
            height: 500px;
            overflow-y: auto;
            font-size: 12px;
            line-height: 1.4;
        }
        .stats-panel {
            width: 300px;
            background-color: white;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        .event-entry {
            margin: 5px 0;
            padding: 5px;
            border-left: 3px solid #00ff00;
            padding-left: 10px;
        }
        .event-memory { border-left-color: #00bfff; }
        .event-search { border-left-color: #ffa500; }
        .event-heartbeat { border-left-color: #ff69b4; }
        .event-connection { border-left-color: #32cd32; }
        .stats-item {
            margin: 10px 0;
            padding: 5px;
            background-color: #f8f9fa;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔥 MCP Memory Service - Real-time Events</h1>
        
        <div id="status" class="status disconnected">
            ❌ Disconnected from SSE stream
        </div>
        
        <div class="controls">
            <button id="connectBtn" class="btn-primary" onclick="connectSSE()">Connect to Events</button>
            <button id="disconnectBtn" class="btn-secondary" onclick="disconnectSSE()" disabled>Disconnect</button>
            <button class="btn-primary" onclick="testMemoryOperations()">Test Memory Operations</button>
            <button class="btn-danger" onclick="clearLog()">Clear Log</button>
        </div>
        
        <div class="events-container">
            <div class="events-log" id="eventsLog">
                <div>🚀 SSE Event Log - Waiting for connection...</div>
            </div>
            
            <div class="stats-panel">
                <h3>📊 Connection Stats</h3>
                <div class="stats-item">
                    <strong>Status:</strong> <span id="statsStatus">Disconnected</span>
                </div>
                <div class="stats-item">
                    <strong>Events Received:</strong> <span id="statsEvents">0</span>
                </div>
                <div class="stats-item">
                    <strong>Connection Time:</strong> <span id="statsTime">-</span>
                </div>
                <div class="stats-item">
                    <strong>Last Event:</strong> <span id="statsLastEvent">-</span>
                </div>
                
                <h3>🎯 Event Types</h3>
                <div class="stats-item">
                    💾 Memory Stored: <span id="statMemoryStored">0</span>
                </div>
                <div class="stats-item">
                    🗑️ Memory Deleted: <span id="statMemoryDeleted">0</span>
                </div>
                <div class="stats-item">
                    🔍 Search Completed: <span id="statSearchCompleted">0</span>
                </div>
                <div class="stats-item">
                    💓 Heartbeats: <span id="statHeartbeat">0</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        let eventSource = null;
        let eventCount = 0;
        let connectionStart = null;
        let eventStats = {
            memory_stored: 0,
            memory_deleted: 0,
            search_completed: 0,
            heartbeat: 0
        };

        function updateStatus(connected) {
            const statusEl = document.getElementById('status');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            const statsStatus = document.getElementById('statsStatus');
            
            if (connected) {
                statusEl.className = 'status connected';
                statusEl.innerHTML = '✅ Connected to SSE stream';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                statsStatus.textContent = 'Connected';
                connectionStart = new Date();
            } else {
                statusEl.className = 'status disconnected';
                statusEl.innerHTML = '❌ Disconnected from SSE stream';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                statsStatus.textContent = 'Disconnected';
                connectionStart = null;
            }
        }

        function addLogEntry(message, type = 'info') {
            const log = document.getElementById('eventsLog');
            const entry = document.createElement('div');
            entry.className = `event-entry event-${type}`;
            entry.innerHTML = `<span style="color: #666;">${new Date().toLocaleTimeString()}</span> ${message}`;
            log.appendChild(entry);
            log.scrollTop = log.scrollHeight;
        }

        function updateStats() {
            document.getElementById('statsEvents').textContent = eventCount;
            document.getElementById('statMemoryStored').textContent = eventStats.memory_stored;
            document.getElementById('statMemoryDeleted').textContent = eventStats.memory_deleted;
            document.getElementById('statSearchCompleted').textContent = eventStats.search_completed;
            document.getElementById('statHeartbeat').textContent = eventStats.heartbeat;
            
            if (connectionStart) {
                const duration = Math.floor((new Date() - connectionStart) / 1000);
                document.getElementById('statsTime').textContent = `${duration}s`;
            }
        }

        function connectSSE() {
            if (eventSource) {
                eventSource.close();
            }
            
            addLogEntry('🔌 Connecting to SSE stream...', 'connection');
            
            eventSource = new EventSource('/api/events');
            
            eventSource.onopen = function(event) {
                updateStatus(true);
                addLogEntry('✅ Connected to SSE stream', 'connection');
            };
            
            eventSource.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    handleEvent(data, event.type || 'message');
                } catch (e) {
                    addLogEntry(`❌ Invalid JSON: ${event.data}`, 'error');
                }
            };
            
            eventSource.addEventListener('memory_stored', function(event) {
                const data = JSON.parse(event.data);
                handleEvent(data, 'memory_stored');
            });
            
            eventSource.addEventListener('memory_deleted', function(event) {
                const data = JSON.parse(event.data);
                handleEvent(data, 'memory_deleted');
            });
            
            eventSource.addEventListener('search_completed', function(event) {
                const data = JSON.parse(event.data);
                handleEvent(data, 'search_completed');
            });
            
            eventSource.addEventListener('heartbeat', function(event) {
                const data = JSON.parse(event.data);
                handleEvent(data, 'heartbeat');
            });
            
            eventSource.addEventListener('connection_established', function(event) {
                const data = JSON.parse(event.data);
                handleEvent(data, 'connection');
            });
            
            eventSource.onerror = function(event) {
                updateStatus(false);
                addLogEntry('❌ SSE connection error', 'error');
            };
        }

        function disconnectSSE() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
            updateStatus(false);
            addLogEntry('🔌 Disconnected from SSE stream', 'connection');
        }

        function handleEvent(data, eventType) {
            eventCount++;
            document.getElementById('statsLastEvent').textContent = eventType;
            
            // Update event type stats
            if (eventStats.hasOwnProperty(eventType)) {
                eventStats[eventType]++;
            }
            
            // Format event message
            let message = '';
            let logType = 'info';
            
            switch (eventType) {
                case 'memory_stored':
                    const hash = data.content_hash ? data.content_hash.substring(0, 12) + '...' : 'unknown';
                    const preview = data.content_preview || 'No preview';
                    message = `💾 <strong>Memory Stored:</strong> ${hash}<br>&nbsp;&nbsp;&nbsp;&nbsp;${preview}`;
                    logType = 'memory';
                    break;
                    
                case 'memory_deleted':
                    const delHash = data.content_hash ? data.content_hash.substring(0, 12) + '...' : 'unknown';
                    const success = data.success ? '✅' : '❌';
                    message = `🗑️ <strong>Memory Deleted:</strong> ${success} ${delHash}`;
                    logType = 'memory';
                    break;
                    
                case 'search_completed':
                    const query = data.query || 'Unknown query';
                    const count = data.results_count || 0;
                    const time = data.processing_time_ms || 0;
                    message = `🔍 <strong>Search:</strong> "${query}" → ${count} results (${time.toFixed(1)}ms)`;
                    logType = 'search';
                    break;
                    
                case 'heartbeat':
                    const connections = data.active_connections || 0;
                    message = `💓 <strong>Heartbeat:</strong> ${connections} active connections`;
                    logType = 'heartbeat';
                    break;
                    
                case 'connection_established':
                    message = `🔌 <strong>Connected:</strong> ${data.message || 'Connection established'}`;
                    logType = 'connection';
                    break;
                    
                default:
                    message = `📨 <strong>${eventType}:</strong> ${JSON.stringify(data)}`;
            }
            
            addLogEntry(message, logType);
            updateStats();
        }

        async function testMemoryOperations() {
            addLogEntry('🚀 Starting test memory operations...', 'info');
            
            try {
                // Store a test memory
                const testMemory = {
                    content: `SSE test memory created at ${new Date().toLocaleString()}`,
                    tags: ['sse-test', 'browser-test', 'demo'],
                    memory_type: 'test',
                    metadata: { source: 'sse_test_page' }
                };
                
                const storeResponse = await fetch('/api/memories', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(testMemory)
                });
                
                if (storeResponse.ok) {
                    const result = await storeResponse.json();
                    addLogEntry(`✅ Test memory stored: ${result.content_hash?.substring(0, 12)}...`, 'info');
                    
                    // Wait a moment, then perform a search
                    setTimeout(async () => {
                        const searchResponse = await fetch('/api/search', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ query: 'SSE test memory', n_results: 3 })
                        });
                        
                        if (searchResponse.ok) {
                            addLogEntry('✅ Test search completed', 'info');
                            
                            // Wait another moment, then delete the memory
                            setTimeout(async () => {
                                if (result.content_hash) {
                                    const deleteResponse = await fetch(`/api/memories/${result.content_hash}`, {
                                        method: 'DELETE'
                                    });
                                    
                                    if (deleteResponse.ok) {
                                        addLogEntry('✅ Test memory deleted', 'info');
                                    }
                                }
                            }, 2000);
                        }
                    }, 2000);
                }
            } catch (error) {
                addLogEntry(`❌ Test operation failed: ${error.message}`, 'error');
            }
        }

        function clearLog() {
            document.getElementById('eventsLog').innerHTML = '<div>🚀 SSE Event Log - Log cleared</div>';
            eventCount = 0;
            eventStats = { memory_stored: 0, memory_deleted: 0, search_completed: 0, heartbeat: 0 };
            updateStats();
        }

        // Auto-connect on page load
        window.onload = function() {
            // connectSSE(); // Uncomment to auto-connect
        };
        
        // Clean up on page unload
        window.onbeforeunload = function() {
            if (eventSource) {
                eventSource.close();
            }
        };
    </script>
</body>
</html>